import mx.containers.TitleWindow;
import mx.managers.PopUpManager;
import mx.events.*;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import mx.controls.Alert;

import mx.core.Application;

import Bugs;
import Form;

//////////////////////////////////////////////////////////////////////////
//  Configuration Variables
//////////////////////////////////////////////////////////////////////////
private var perPage:int  = 20;

//////////////////////////////////////////////////////////////////////////
//  Bindable Variables
//////////////////////////////////////////////////////////////////////////
[Bindable] private var gridXMLList:XMLList = new XMLList();
[Bindable] private var rii_type:Array = ["bug","task","enhancement"];
[Bindable] private var rii_status:Array = ["new","started","fixed","closed","duplicate"];
[Bindable] private var rii_priority:Array = ["critical","high","medium","low"];

// Stored the url object returned from parseURL
private var _url:Object  = new Object();
// The current page of bugs
private var page:int  = 0;

private function initBugsApp() : void
{
    // Need to strip off @swf which is used as the embed string
    _url = parseURL((Application.application.url
        ).replace("/@swf","/"));

    getIssues();
}

private function initReportApp() : void
{
    // Need to strip off @swf which is used as the embed string
    _url = parseURL((Application.application.url
        ).replace("/@swf","/")); 
}

//////////////////////////////////////////////////////////////////////////
//  Main Issues / Front Page
//////////////////////////////////////////////////////////////////////////
private function getIssues():void
{
    var index:int = page * perPage + 1;
    var range:String = _url.fullpath + "a" + index.toString() 
        + ":g"+(index+perPage).toString() + "?format=xml";

    get(range,function (event:ResultEvent):void 
        {
            gridXMLList = new XMLList();
            var y:int = 1;
            for each (var item:XML in event.result.row)
            {
                var tmp:XML = new XML("<row></row>");
        
                for(var i:int = 0; i < item.column.length(); i++)
                {
                    tmp.appendChild(new XML("<column"+(i+1)
                        + ">"+item.column[i]+"</column"+(i+1)+">"));
                }
                gridXMLList += tmp;
                y++;
            }
        });
}
//////////////////////////////////////////////////////////////////////////
//  Dialog used to Report Issues
//////////////////////////////////////////////////////////////////////////
private function reportIssue(summary:String,type:String,
    desc:String,status:String,assign:String,priority:String) : void
{
    // TODO : when creating an issue, get a new id by selecting every 
    // id, picking the last and adding 1. obvious race condition when 
    // 2 people make an issue at the same time. fix later
    get(_url.fullpath + "a?format=xml",function(event:ResultEvent):void
    {
        var rows:XMLList = event.result.row;
        var id:int = parseInt(rows[rows.length()-1]) + 1;
        
        var xml_str:String = "<post><action>create</action><value>"
            +"<cell>"+id+"</cell><cell>"+type+"</cell><cell>"
            +summary+"</cell><cell>"+status+"</cell>"
            +"</value></post>";

        post(_url.fullpath + "a?last&format=xml",xml_str, 
            function(e:ResultEvent):void
        {
            closeReportDialog(null);
            getIssues();
        });   
    });
}

private function closeReportDialog(event : CloseEvent) : void 
{
    PopUpManager.removePopUp(this);
}
 
private function openReportDialog() : void
{
    var pop1:TitleWindow = 
        TitleWindow(PopUpManager.createPopUp(this, Form, true));  
    PopUpManager.centerPopUp(pop1);
}
//////////////////////////////////////////////////////////////////////////
//  Parses a url so http://example.org:8000/a/path
//  obj.fullpath = "http://example.org:8000/a/path";
//  obj.path     = ["a", "path"];
//  obj.domain   = "example.org";
//  obj.port     = 8000
//////////////////////////////////////////////////////////////////////////
private function parseURL(orig:String):Object
{
    var tmp:Object = new Object();

    tmp.fullpath = orig;
    tmp.path = (tmp.fullpath.replace("http://","").split("/"));

    var tmp_domain:Array = (tmp.path[0]).split(":");
    tmp.path.shift();

    tmp.domain = tmp_domain[0];
    tmp.port   = (tmp_domain[1] == undefined) ? 80 : tmp_domain[1];
    return tmp;

}

//////////////////////////////////////////////////////////////////////////
//  Sends a get request to url, calls callback when data is returned
//////////////////////////////////////////////////////////////////////////
private function get(url:String, callback:Function):void
{
    var tmp:HTTPService = new HTTPService();
    tmp.method = "GET";
    tmp.url = url;
    tmp.resultFormat = "e4x";
    tmp.addEventListener("result", callback);
    tmp.send();
}

private function post(url:String,data:String, callback:Function):void
{
    var tmp:HTTPService = new HTTPService();
    var variables:Object = new XML(data);
    tmp.method = "POST";
    tmp.url = url;
    tmp.contentType = "application/xml"
    tmp.resultFormat = "e4x";
    tmp.addEventListener("result", callback);
    tmp.send(variables);
}